from rest_framework import serializers
from .models import City, DataCenter, Host, HostPassword, CityHostStatistics, IDCHostStatistics
import random
import string


class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = '__all__'


class DataCenterSerializer(serializers.ModelSerializer):
    city = CitySerializer(read_only=True)
    city_id = serializers.PrimaryKeyRelatedField(
        queryset=City.objects.all(),
        source='city',
        write_only=True
    )

    class Meta:
        model = DataCenter
        fields = '__all__'


class HostSerializer(serializers.ModelSerializer):
    data_center = DataCenterSerializer(read_only=True)
    data_center_id = serializers.PrimaryKeyRelatedField(
        queryset=DataCenter.objects.all(),
        source='data_center',
        write_only=True
    )
    is_reachable = serializers.SerializerMethodField()

    class Meta:
        model = Host
        fields = '__all__'
        extra_kwargs = {
            'status': {'required': False}
        }

    def get_is_reachable(self, obj):
        # 这里简化实现，实际应该调用ping检测
        # 真实项目中可以使用subprocess调用系统ping命令
        return True


class HostPasswordSerializer(serializers.ModelSerializer):
    class Meta:
        model = HostPassword
        fields = ['root_password', 'last_updated']
        read_only_fields = ['last_updated']
        extra_kwargs = {
            'root_password': {'write_only': True}
        }


class CityHostStatisticsSerializer(serializers.ModelSerializer):
    city_name = serializers.ReadOnlyField(source='city.name')

    class Meta:
        model = CityHostStatistics
        fields = '__all__'


class IDCHostStatisticsSerializer(serializers.ModelSerializer):
    idc_name = serializers.ReadOnlyField(source='idc.name')
    city_name = serializers.ReadOnlyField(source='idc.city.name')

    class Meta:
        model = IDCHostStatistics
        fields = '__all__'

def generate_random_password(length=16):
    chars = string.ascii_letters + string.digits + '!@#$%^&*'
    return ''.join(random.choice(chars) for _ in range(length))